package tk.mybatis.springboot.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import tk.mybatis.springboot.model.TSysUser;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by NightDream on 2017/9/12.
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {
    Logger log = LoggerFactory.getLogger(LoginInterceptor.class);
    /**
     * 重定向视图名称前缀
     */
    private static final String REDIRECT_VIEW_NAME_PREFIX = "redirect:";

    /**
     * "重定向URL"参数名称
     */
    private static final String REDIRECT_URL_PARAMETER_NAME = "redirectUrl";

    /**
     * 默认登录URL
     */
    private static final String DEFAULT_LOGIN_URL = "/user/loginIndex";

    /**
     * 登录URL
     */
    private String loginUrl = DEFAULT_LOGIN_URL;

    /**
     * 请求前处理
     *
     * @param request  HttpServletRequest
     * @param response HttpServletResponse
     * @param handler  处理器
     * @return 是否继续执行
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        TSysUser user = (TSysUser) request.getSession().getAttribute("sysuser");
        if (user != null) {
            log.info("用户已经登陆");
            return true;
        } else {
            response.sendRedirect(request.getContextPath() + loginUrl);
            log.info("用户未登陆，跳转至登陆页面");
            return false;
        }
    }

    /**
     * 请求后处理
     *
     * @param request      HttpServletRequest
     * @param response     HttpServletResponse
     * @param handler      处理器
     * @param modelAndView 数据视图
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    /**
     * 获取登录URL
     *
     * @return 登录URL
     */
    public String getLoginUrl() {
        return loginUrl;
    }

    /**
     * 设置登录URL
     *
     * @param loginUrl 登录URL
     */
    public void setLoginUrl(String loginUrl) {
        this.loginUrl = loginUrl;
    }
}
